package com.management.department.teacherinfosystem.Controller;

import com.management.department.teacherinfosystem.Entity.ServiceContribution;
import com.management.department.teacherinfosystem.Entity.User;
import com.management.department.teacherinfosystem.Repository.ServiceContributionRepository;
import com.management.department.teacherinfosystem.Repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/service-contrib")
@CrossOrigin(origins = "*")
public class ServiceContributionController {

    @Autowired private ServiceContributionRepository repository;
    @Autowired private UserRepository userRepository;

    // mine
    @GetMapping("/mine")
    @Transactional(readOnly = true)
    public ResponseEntity<?> mine(){
        User current = currentUser();
        if(current == null) return ResponseEntity.status(401).body("未登录");
        return ResponseEntity.ok(repository.findByUserId(current.getId()));
    }

    @PostMapping
    @Transactional
    public ResponseEntity<?> create(@RequestBody Map<String,Object> payload){
        User current = currentUser();
        if(current == null) return ResponseEntity.status(401).body("未登录");
        ServiceContribution s = new ServiceContribution();
        s.setUserId(current.getId());
        s.setWorkType((String) payload.get("work_type"));
        s.setCategory((String) payload.get("category"));
        s.setContent((String) payload.get("content"));
        String hours = (String) payload.get("target_or_hours");
        if (hours == null || hours.isBlank()) {
            return ResponseEntity.badRequest().body("时长为必填");
        }
        s.setTargetOrHours(hours);
        repository.save(s);
        return ResponseEntity.ok(Map.of("id", s.getId()));
    }

    @PutMapping("/{id}")
    @Transactional
    public ResponseEntity<?> update(@PathVariable("id") Long id, @RequestBody Map<String,Object> payload){
        ServiceContribution s = repository.findById(id).orElse(null);
        if(s == null) return ResponseEntity.notFound().build();
        User current = currentUser();
        if(current == null || !Objects.equals(current.getId(), s.getUserId())) return ResponseEntity.status(403).body("无权修改");
        s.setWorkType((String) payload.getOrDefault("work_type", s.getWorkType()));
        s.setCategory((String) payload.getOrDefault("category", s.getCategory()));
        s.setContent((String) payload.getOrDefault("content", s.getContent()));
        String hours = (String) payload.get("target_or_hours");
        if (hours == null || hours.isBlank()) {
            return ResponseEntity.badRequest().body("时长为必填");
        }
        s.setTargetOrHours(hours);
        // 回到待审核，清空审核信息
        s.setStatus("PENDING");
        s.setReviewOpinion(null);
        s.setReviewerId(null);
        s.setReviewTime(null);
        repository.save(s);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/{id}")
    @Transactional
    public ResponseEntity<?> delete(@PathVariable("id") Long id){
        ServiceContribution s = repository.findById(id).orElse(null);
        if(s == null) return ResponseEntity.notFound().build();
        User current = currentUser();
        if(current == null || !Objects.equals(current.getId(), s.getUserId())) return ResponseEntity.status(403).body("无权删除");
        repository.deleteById(id);
        return ResponseEntity.ok().build();
    }

    // admin list & search
    @GetMapping("/all")
    @Transactional(readOnly = true)
    public ResponseEntity<?> all(@RequestParam(value = "type", required = false) String type,
                                 @RequestParam(value = "status", required = false) String status,
                                 @RequestParam(value = "startDate", required = false) String startDate,
                                 @RequestParam(value = "endDate", required = false) String endDate){
        User current = currentUser();
        if(current == null) return ResponseEntity.status(401).body("未登录");
        boolean isAdmin = current.getUserRoles().stream().anyMatch(ur -> ur.getRole() != null && "admin".equalsIgnoreCase(ur.getRole().getName()));
        if(!isAdmin) return ResponseEntity.status(403).body("权限不足");
        return ResponseEntity.ok(repository.search(
                blankToNull(type), blankToNull(status), parseDate(startDate), parseDate(endDate)
        ));
    }

    @PostMapping("/{id}/review")
    @Transactional
    public ResponseEntity<?> review(@PathVariable("id") Long id, @RequestBody Map<String,Object> payload){
        User current = currentUser();
        if(current == null) return ResponseEntity.status(401).body("未登录");
        boolean isAdmin = current.getUserRoles().stream().anyMatch(ur -> ur.getRole() != null && "admin".equalsIgnoreCase(ur.getRole().getName()));
        if(!isAdmin) return ResponseEntity.status(403).body("权限不足");
        ServiceContribution s = repository.findById(id).orElse(null);
        if(s == null) return ResponseEntity.notFound().build();
        String st = String.valueOf(payload.get("status"));
        if(!"APPROVED".equals(st) && !"REJECTED".equals(st)) return ResponseEntity.badRequest().body("状态无效");
        s.setStatus(st);
        s.setReviewOpinion((String) payload.get("opinion"));
        s.setReviewerId(current.getId());
        s.setReviewTime(new Date());
        repository.save(s);
        return ResponseEntity.ok().build();
    }

    private Date parseDate(Object v){ if(v==null) return null; try{ return new SimpleDateFormat("yyyy-MM-dd").parse(String.valueOf(v)); } catch(Exception e){ return null; } }
    private String blankToNull(String s){ return (s==null || s.isBlank()) ? null : s; }

    private User currentUser(){
        org.springframework.security.core.Authentication auth =
                org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
        String currentUsername = auth == null ? null : auth.getName();
        return currentUsername == null ? null : userRepository.findByUsernameWithRoles(currentUsername).orElse(null);
    }
}


